package com.yqw.onlineDocs.manager;

import cn.hutool.core.collection.CollUtil;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionChoice;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import com.yqw.onlineDocs.common.ErrorCode;
import com.yqw.onlineDocs.exception.BusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * AI管理器
 */
@Service
public class AiManager {

    @Resource
    private ArkService aiService;

    /**
     * 调用AI服务进行聊天回复
     *
     * @param userPrompt
     * @return
     */
    public String doChar(String userPrompt){
        return doChar("", userPrompt);
    }

    /**
     * 调用AI服务进行聊天回复
     *
     * @param systemPrompt
     * @param userPrompt
     * @return
     */
    public String doChar(String systemPrompt, String userPrompt){
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(userPrompt).build();
        messages.add(systemMessage);
        messages.add(userMessage);
        return doChar(messages);
    }

    /**
     * 调用AI服务进行聊天回复(消息列表形式)
     *
     * @param messages 聊天消息列表
     * @return
     */
    public String doChar(List<ChatMessage> messages){
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
                .model("deepseek-v3-250324")
                .messages(messages)
                .build();
        List<ChatCompletionChoice> choices = aiService.createChatCompletion(chatCompletionRequest).getChoices();
        if(CollUtil.isNotEmpty(choices)){
            return (String) choices.get(0).getMessage().getContent();
        }
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "AI服务调用失败");
    }

}
